package com.easpeed.comon.utils

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.widget.ProgressBar
import androidx.core.app.ActivityCompat
import androidx.core.content.FileProvider
import com.easpeed.elevator.R
import com.easpeed.user.dialog.UserDialogHelper.showDownloadDialog
import java.io.File

/**
 * Created by bigyu on 2025-01-24 09:55
 * com.easpeed.comon.utils
 */
class DownloadHelper(val mContext: Context) {

    var call: okhttp3.Call? = null

    @JvmOverloads
    fun init(title: String, url: String, sureClick: (() -> Unit)? = null, cancelClick: (() -> Unit)? = null) {
        call?.cancel()
        showDownloadDialog(mContext, title, "", sureClick = {
            if (checkPermission(mContext as Activity)) {
                val progress = it?.getView(R.id.progress) as ProgressBar
                val path: String = mContext.externalCacheDir?.absolutePath.toString()
                val file = File(path + File.separator + "update.apk")
                if (file.exists()) {
                    file.delete()
                }
                com.bigyu.utils.Logger.e("TAG", "init: ${file.absolutePath}")
                it.setText(R.id.msg, "开始下载")
                it.setText(R.id.sure, "下载")
                it.setEnable(R.id.sure, false)

                call = SimpleFileDownloader.downloadFile(url, file) { mPprogress, msg, success ->
                    Handler(Looper.getMainLooper()).post {
                        progress.progress = mPprogress
                        if (success) {
                            it.setText(R.id.msg, "下载中: $mPprogress%")
                            if (mPprogress == 100) {
                                it.setEnable(R.id.sure, true)
                                it.setText(R.id.sure, "安装")
                                it.dismiss()
                                installApk(file.absolutePath, mContext as Activity)
                            }

                        } else {
                            it.setText(R.id.sure, "重试")
                            it.setEnable(R.id.sure, true)
                            it.setText(R.id.msg, msg)
                        }
                    }
                    com.bigyu.utils.Logger.e("TAG", "init: $it")
                }

            }


        }, cancelClick = {
            call?.cancel()
        })


    }

    private fun checkPermission(activity: Activity): Boolean {
        // Step 1: 检查存储权限（仅 Android 6.0+）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(
                    activity,
                    Manifest.permission.READ_EXTERNAL_STORAGE
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                ActivityCompat.requestPermissions(
                    activity,
                    arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
                    1001
                )
                return false
            }
        }

        // Step 2: 检查安装权限（仅 Android 8.0+）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (!activity.packageManager.canRequestPackageInstalls()) {
                // 跳转到设置页面授权
                val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).apply {
                    data = Uri.parse("package:${activity.packageName}")
                }
                activity.startActivity(intent)
                return false
            }
        }
        return true
    }


    fun installApk(apkFilePath: String, activity: Activity) {
        val apkFile = File(apkFilePath)
        if (!apkFile.exists()) {
            println("APK file does not exist at: $apkFilePath")
            return
        }
        // Step 3: 准备安装 Intent
        val intent = Intent(Intent.ACTION_VIEW).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK

            val apkUri: Uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                // 使用 FileProvider 处理文件权限（Android 7.0+）
                FileProvider.getUriForFile(
                    activity,
                    "${activity.packageName}.fileProvider",
                    apkFile
                )
            } else {
                // 直接使用文件 URI（Android 7.0 以下）
                Uri.fromFile(apkFile)
            }

            setDataAndType(apkUri, "application/vnd.android.package-archive")

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                flags = flags or Intent.FLAG_GRANT_READ_URI_PERMISSION
            }
        }

        // Step 4: 启动安装
        activity.startActivity(intent)
    }

}